package com.ovo.chatRobot.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import net.sf.json.JSONObject;

public class Tuling {
	public static final String url = "https://www.tuling123.com/openapi/api";     

    /**
	 * 向后台发送post请求
	 */
	public static String SendPost(String param) {
		OutputStreamWriter out = null;
		BufferedReader in = null;
		StringBuffer result = new StringBuffer();
		try {									
			URL realUrl = new URL(url);
			//处理SSL请求证书问题
			if("https".equalsIgnoreCase(realUrl.getProtocol())){
	            SslUtils.ignoreSsl();
	        }
			HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(true);
			conn.setRequestMethod("POST");
			conn.setConnectTimeout(50000);
			conn.setReadTimeout(50000);
			conn.setRequestProperty("Content-Type", "application/json");
			conn.setRequestProperty("Accept", "application/json");
			conn.setRequestProperty("Authorization", "token");
			conn.setRequestProperty("tag", "htc_new");

			JSONObject obj = new JSONObject();
			obj.element("key", "3de25f272978430f88bf834916ad35b8");//ovo:f15f8c5d351642ff8c4a1ff3668707b1
			obj.element("info", param);

			conn.connect();
			out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			out.write(obj.toString());
			out.flush();
			out.close();

			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

			String line = "";
			while ((line = in.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		new JSONObject();
		JSONObject robot = JSONObject.fromObject(result.toString());
		String text = robot.getString("text");
		if (robot.has("url")) // 在此处做判断，包含字段的话再继续从JSON中获取url字段的内容
		{
			String url = robot.getString("url");
			text = text + "\n 链接：" + url;
		}

		if (robot.has("list")) // 在此处做判断，包含字段的话再继续从JSON中获取list字段的内容
		{
			String list = robot.getString("list");
			text = text + "\n 表格：" + list;
		}
		
		return text;
	}

}
